import { goodsCount, goodsList } from "../../request/api"
const state = {
    //列表
    list: [],
    //分页
    count: 0,
    page: 1,
    size:2
}
const mutations = {
    changeList(state, val) {
        state.list = val
    },
    changeCount(state, val) {
        state.count=val
    },
    changePage(state, val) {
        state.page=val
    }
}
const actions = {
    asyncChangeList(context) {
        goodsList({ page: context.state.page, size: context.state.size }).then(res => {
            //1.当前页无数据时 手动设为空数组 防止报错
            let arr = res.data.list ? res.data.list : [];
            //2.当前页无数据时 应该跳到前一页去 同时最小页数应为1 再重新请求列表数据
            if (arr.length <= 0 && context.state.page > 1) {
                context.commit("changePage", context.state.page - 1);
                context.dispatch("asyncChangeList")
            }

            context.commit("changeList",arr)
        })
    },
    asyncChangeCount(context) {
        goodsCount().then(res => {
            context.commit("changeCount",res.data.list[0].total)
        })
    },
    //当前页数据变化时 重新请求当前所在页，重新请求列表数据
    asyncChangePage(context, num) {
        context.commit("changePage", num);
        context.dispatch("asyncChangeList")
    }
}
const getters = {
    list(state) {
        return state.list
    },
    count(state) {
        return state.count
    },
    size(state) {
        return state.size
    }
}
export default {
    state, mutations, actions, getters,
    namespaced:true
}